import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, Table,Popconfirm,Button,message, } from 'antd';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import router from 'umi/router';
import Ellipsis from '../../../components/Ellipsis';
import PropTypes from 'prop-types';
import Separate from './Separate';
import { PlusOutlined } from '@ant-design/icons';


const mapStateToProps = (state: any) => ({
  goodMng: state.goodMng,
  loading: state.loading.effects['goodMng/postFetchPage'],
  menud:state.menu,
});
class GoodMng extends PureComponent<any, any>  {
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      brand:[],
      series: [],
      extendStatus: false,
      formValues: {},
      pagination: {
        current: 1,
        pageSize: 10,
      },
      goodsTypeOptions:[],
    };
  }

  // 重置品牌
  setBrand = () => {
    this.searchForm.current.resetFields(['brandId', 'carSeries',]);
    this.props.dispatch({
      type: 'vehicleInfoQuery/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: e => {
        this.setState({
          brand: e.data.map(e => ({
            label: e.brandName,
            value: e.brandCode,
          })),
          series: [],
          type: [],
        });
      },
    });
  };

  // 重置车系
  setSeries = () => {
    this.searchForm.current.resetFields(['carSeries',]);

    this.setState({ series: [], type: [] });
    const brandId = this.searchForm.current.getFieldValue('brandId');
    brandId &&
      this.props.dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId,
        },
        callback: e => {
          this.setState({
            series: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  };

  // 重置车型
  setType = () => {
    this.searchForm.current.resetFields(['styleId']);
    this.setState({ type: [] });
    const brandId = this.searchForm.current.getFieldValue('brandId');
    const seriesId = this.searchForm.current.getFieldValue('seriesId');
    brandId &&
      seriesId &&
      this.props.dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: e => {
          this.setState({
            type: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;
    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location;
      let values = {
        ...pagination
      };
      if ( sourcePage === 'goodsMng' ) {
        //  详情返回
        const tempValues = sessionStorage.getItem('goodsMngSearchValues')
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {})
        };
        this.setState({
          extendStatus: true,
        })
      }
      const { current, pageSize, ...rest } = values;
      this.setState({
        formValues: {
          ...formValues,
          ...rest,
        },
        pagination: {
          current,
          pageSize
        }
      }, () => {
        const { formValues, pagination } = this.state
        this.searchForm.current.setFieldsValue({
          ...formValues,
        });
        dispatch({
          type: 'goodMng/postFetchPage',
          payload: { url: '/optshop/base/goods/list/search', ...formValues, ...pagination },
        });
      })
    })
    this.setBrand();
    this.getGoodsType();
  }
  //获取商品类型新阿拉数据
  getGoodsType=()=>{
    this.props.dispatch({
      type: 'goodMng/getDataWithRes',
      payload: { url: '/optshop/base/goodstype/query/drop/list',},
      callback: (res:any) => {
        this.setState({ 
          goodsTypeOptions: res?.data?.list?.map((item:any)=>{
            return {
              label: item.goodsTypeName,
              value: item.goodsTypeId
            }
           }),
        });
       }
    })
  }
  componentWillUnmount() {
    if(this.unlisten) {
      this.unlisten();
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'goodMng/initData',
    });
  }
 
  handleFormReset = (fields: any) => {
    this.searchForm.current.setFieldsValue({})
    this.setState({
      formValues: {},
      pagination: {
        current: 1,
        pageSize: 10,
      },
    });
  }

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    const params = {
      ...formValues,
      current,
      pageSize,
      ...filters,
    };
    this.setState({
      pagination: {
        current,
       pageSize,
      }
    }, () => {
      dispatch({
        type: 'goodMng/postFetchPage',
        payload: { url: '/optshop/base/goods/list/search', ...params },
      });
    })
  }
  //上架
  online =(record:any)=>{
    let params = {
      sid: record.sid,
      spuStatus: 1
    }
   this.props.dispatch({
      type: 'goodMng/postObjWithRes',
      payload: {
        url: '/optshop/base/goods/change/status',
        ...params
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
         message.success('上架成功');
         const pagination = {
          current: 1,
          pageSize: 10,
        };
         this.props.dispatch({
            type: 'goodMng/postFetchPage',
            payload: { url: '/optshop/base/goods/list/search', ...pagination },
          });
        }
      },
    });
  }
  //下架
  offline=(record:any)=>{
    let params = {
      sid: record.sid,
      spuStatus: 2
    }
   this.props.dispatch({
      type: 'goodMng/postObjWithRes',
      payload: {
        url: '/optshop/base/goods/change/status',
        ...params
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('下架成功');
          const pagination = {
            current: 1,
            pageSize: 10,
          };
          this.props.dispatch({
            type: 'goodMng/postFetchPage',
            payload: { url: '/optshop/base/goods/list/search', ...pagination },
          });
        }
      },
    });
  }
  //作废
  discard=(record:any)=>{
    let params = {
      sid: record.sid,
      spuStatus: 3
    }
   this.props.dispatch({
      type: 'goodMng/postObjWithRes',
      payload: {
        url: '/optshop/base/goods/change/status',
        ...params
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('作废成功');
          const pagination = {
            current: 1,
            pageSize: 10,
          };
          this.props.dispatch({
            type: 'goodMng/postFetchPage',
            payload: { url: '/optshop/base/goods/list/search', ...pagination },
          });
        }
      },
    });
  }
  //删除
  handleDelete = (record:any) =>{
   this.props.dispatch({
      type: 'goodMng/getData',
      payload: {
        url: '/optshop/base/goods/delete',
        sid: record.sid,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          const pagination = {
            current: 1,
            pageSize: 10,
          };
          this.props.dispatch({
            type: 'goodMng/postFetchPage',
            payload: { url: '/optshop/base/goods/list/search', ...pagination },
          });
        }
      },
    });
  }
  handleAdd =()=>{
    const { formValues, pagination } = this.state;
    const searchValues = {
      ...formValues,
      ...pagination
    };
    sessionStorage.setItem('goodsMngSearchValues', JSON.stringify(searchValues));
    router.push('/goodsManager/goodsMng/goodAdd');
  }
  handleView =(record:any)=>{
    sessionStorage.setItem('spuId', JSON.stringify(record.spuId || ''));
    const { formValues, pagination } = this.state;
    const searchValues = {
      ...formValues,
      ...pagination
    };
    sessionStorage.setItem('goodsMngSearchValues', JSON.stringify(searchValues));
    router.push('/goodsManager/goodsMng/goodDetail');
  }
  handleEdit = (record:any) =>{
    message.success('加载中，请稍候...')
    //获取详情
    this.props.dispatch({
      type: 'goodMng/getData',
      payload: {
        url: '/optshop/base/goods/detail/search',//待修改url
        spuId: record.spuId,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
       const data = response.data;
       const {sid,benefits,brandId,brandName,buyers,carSeries,carTypes,goodsCategoryName,goodsDesc,goodsMaxPrice,goodsPlatform, goodsQrPic,
        goodsTypeId, icon, ifSendBySupplier,isHot, payType,pic,spuName, spuTotalAmount,validDate,saleTime,endTime,spuStatus,spuId,goodsAttachment}=data;
        sessionStorage.setItem('updateGoodId', JSON.stringify(sid));
        const params1 = {
         benefits,brandId,brandName,buyers,carSeries,carTypes,goodsCategoryName,goodsDesc,goodsMaxPrice,goodsPlatform, goodsQrPic,
        goodsTypeId, icon, ifSendBySupplier,isHot, payType,pic,spuName, spuTotalAmount,validDate,saleTime,endTime,spuStatus,spuId,goodsAttachment
        }
        sessionStorage.setItem('goodBasicInfo', JSON.stringify(params1));
        const {goodsSpecFlag, skus:[{attributeInputMethod,goodsPrice,discountPrice,attributeList}]}=data;
        const params2 =  {attributeInputMethod:Number(attributeInputMethod),goodsSpecFlag:Number(goodsSpecFlag),goodsPrice,discountPrice,attributeList};
        sessionStorage.setItem('goodsaleInfo', JSON.stringify(params2));
      const { formValues, pagination } = this.state;
      const searchValues = {
        ...formValues,
        ...pagination
      };
      sessionStorage.setItem('goodsMngSearchValues', JSON.stringify(searchValues));
      router.push('/goodsManager/goodsMng/goodEdit');
        }
      },
    });
  }
  render() {
    const {
      goodMng: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { brand,  series, extendStatus, goodsTypeOptions } = this.state;
    const status = ['未上架', '已上架', '已下架', '已作废'];
    const textColor = ['black', 'aqua', 'limegreen', 'tomato'];
    const searchItems = [
      {
        type: 'select',
        title: `品牌`,
        key: 'brandId',
            selectOptions: brand,
            onChange: () => {
              this.setSeries();
            },
      },
      {
        type: 'select',
        title: `车系`,
        key: 'carSeries',
        selectOptions: series,
      },
    {
      type: 'input',
      title: `商品名称`,
      key: 'spuName',
      maxLength: 20,
    },
    {
      type: 'select',
      title: `商品类型`,
      key: 'goodsTypeId',
      selectOptions: goodsTypeOptions,
    },
    {
      type: 'select',
      title: `商品状态`,
      key: 'spuStatus',
      keyValue: ['key', 'value'],
      selectOptions: [
        {key:0, value:'未上架'},
        {key:1, value:'已上架'},
        {key:2, value:'已下架'},
        {key:3, value:'已作废'},
      ],
    },

  ];

  const columns = [
      {
        title: `品牌`,
        dataIndex: 'brandName',
      },
      {
        title: `车系`,
        dataIndex: 'carSeriesName',
      },
    {
      title: `商品名称`,
      dataIndex: 'spuName',
    },
      {
        title: `商品价格(元)`,
        dataIndex: 'goodsPriceRange',
      },
    {
      title: `商品类型`,
      dataIndex: 'goodsTypeName',
    },
    {
      title: `商品描述`,
      dataIndex: 'goodsDesc',
      render: (text: string) => {
        return (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        );
      },
    },
    {
      title: `商品状态`,
      dataIndex: 'spuStatus',
      render(val: number) {
        return (
        <span style={{color: textColor[val]}}>
         {status[val]}
        </span>)
      },
    },
    {
      title: `是否热门`,
      dataIndex: 'isHot',
      render: (txt: number) => {
        return txt == 1 ? '是' : '否';
      },
    },
    {
      title: `有效日期`,
      dataIndex: 'validDate',
    },
    {
      title: `商品总量`,
      dataIndex: 'spuTotalAmount',
    },
    {
      title: '上/下架',
      dataIndex: 'opt',
      width: 100,
      fixed: 'right',
      render: (text:any, record:any) => {
        switch (record.spuStatus) {
          case 0://未上架
            return (
              <div>
                <Popconfirm title="确定要上架该商品吗?" onConfirm={() => this.online.bind(this)(record)}>
                  <a>上架</a> 
                </Popconfirm>
              </div>
            );
          case 1://已上架
            return (
              <div>
                <Popconfirm title="确定要下架该商品吗?" onConfirm={() => this.offline.bind(this)(record)}>
                  <a>下架</a>
                </Popconfirm>
              </div>
            );
          case 2://已下架
            return (
              <div>
                <Popconfirm title="确定要上架该商品吗?" onConfirm={() => this.online.bind(this)(record)}>
                  <a>上架</a>
                </Popconfirm>
              &nbsp;&nbsp;
                <Popconfirm title="确定要作废该商品吗?" onConfirm={() => this.discard.bind(this)(record)}>
                <a>作废</a>
                </Popconfirm>
              </div>
            );
          case 3:
            return (//作废
             ''
            );
          default:
        }
      },
    },
    {
      title: `操作`,
      dataIndex: '操作',
      fixed: 'right',
      width: 100,
      render: (text:any, record:any) => {
        switch (record.spuStatus) {
          case 0://未上架
            return (
              <div>
                 <a onClick={()=>{this.handleView(record)}}>查看</a> 
                 &nbsp;&nbsp;
                 <a onClick={()=>{this.handleEdit(record)}}>编辑</a> 
                 &nbsp;&nbsp;
                <Popconfirm title="确定要删除该商品吗?" onConfirm={() => this.handleDelete.bind(this)(record)}>
                  <a>删除</a> 
                </Popconfirm>
              </div>
            );
          case 1://已上架
            return (
              <div>
                  <a onClick={()=>{this.handleView(record)}}>查看</a> 
                  &nbsp;&nbsp;
                 <a style={{ pointerEvents: 'none', cursor: 'default', opacity: 0.5, textDecoration:'none', color:'grey' }}>编辑</a> 
                 &nbsp;&nbsp;
                  <a style={{ pointerEvents: 'none', cursor: 'default', opacity: 0.5, textDecoration:'none', color:'grey' }}>删除</a> 
              </div>
            );
          case 2://已下架
            return (
              <div>
                  <a onClick={()=>{this.handleView(record)}}>查看</a> 
                  &nbsp;&nbsp;
                 <a onClick={()=>{this.handleEdit(record)}}>编辑</a> 
                 &nbsp;&nbsp;
                  <a style={{ pointerEvents: 'none', cursor: 'default', opacity: 0.5, textDecoration:'none', color:'grey' }}>删除</a> 
              </div>
            );
          case 3:
            return (//作废
             <div>
                <a onClick={()=>{this.handleView(record)}}>查看</a> 
                 &nbsp;&nbsp;
                 <a style={{ pointerEvents: 'none', cursor: 'default', opacity: 0.5, textDecoration:'none', color:'grey' }}>编辑</a> 
                 &nbsp;&nbsp;
                <Popconfirm title="确定要删除该商品吗?" onConfirm={() => this.handleDelete.bind(this)(record)}>
                  <a>删除</a> 
                </Popconfirm>
             </div>
            );
          default:
        }
      },
    },
  ];
  const separateList = [
    {
      title: list[0]?.onSaleSpus || 0,
      text: '在售SPU',
      key: 1,
    },
    {
      title: list[0]?.onSaleSkus || 0,
      text: '在售SKU',
      key: 2,
    },
    {
      title: list[0]?.onLineSkus || 0,
      text: '上架SKU',
      key: 3,
    },
  ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    return (
      <div>
        <Card bordered={false}>
        <Card>
          <Separate list={separateList}></Separate>
        </Card>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{
              type: 'goodMng/postFetchPage',
              url: '/optshop/base/goods/list/search',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={(val: any) => {
              const { pagination } = this.state;
              return {
                ...val,
                ...pagination,
              };
            }}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
        <div>
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => this.handleAdd()}
          >
            新增
          </Button>
          </div>
        <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(GoodMng);

